import { GLBook } from "./GLBook";
import { GLItem } from "./GLItem";
import { GLFolderLike } from "./GLFolderLike"
import { GLAPI } from "./GLAPI.service"
export class GLFolder extends GLFolderLike {
    private content: GLItem[];
    private childMap = new Map<String, GLItem>();
    constructor(data, glAPI: GLAPI, parentFolder?: GLFolder) {
        super(parentFolder, data.name, data.id);
        this.content = [];
        if (data.folders) {
            this.content = this.content.concat(data.folders.map((info) => new GLFolder(info, glAPI, this)));
        }
        else {
          console.log("No folders?");
          console.log(data);
        }
        if (data.books) {
            this.content = this.content.concat(
                data.books.map((info) => new GLBook(info, glAPI, this))
            );
        }
        this.available = true;
    }

    public getContent() {
      return this.content;
    }

    isAvailable() {
      return true;
    }

    registerChild(item: GLItem) {
      this.childMap.set(item.id, item);
      super.registerChild(item);
    }

    getChildByID(id: String) {
      console.log("Request for " + id);
      console.log("I'm " + this.id);
      let tr = this.childMap.get(id);
      console.log(tr);
      if (!tr) {
        console.log("Didn't find it.");
      }
      return tr;
    }

    getChildDeep(id: string) {
      let shallowResult = this.getChildByID(id);
      if (shallowResult) {
        return Promise.resolve(shallowResult);
      }
      let ind = id.lastIndexOf("/");
      if (ind < 0) {
        // it's not there
        return Promise.resolve(null);
      }
      return this.getChildDeep(id.substr(0, ind)).then((parent) => {
        if (parent && parent.asFolder) {
          return parent.asFolder();
        }
      }).then(() => {
        // should exist now
        return this.getChildByID(id);
      });
    }
}
